package com.atguigu.spring5.aop;

import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JdkProxy {


    public static void main(String[] args) {
        // 创建接口实现类的代理对象
        Class[] interfaces = {UserDao.class};

        UserDaoImpl userDao = new UserDaoImpl();
        UserDao o = (UserDao) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = o.add(1, 2);
        System.out.println(add);
    }
}

class UserDaoProxy implements InvocationHandler {
    // 把创建的是谁的代理对象 ，把谁 要传递过来
    // 有参构造传递
    private Object obj;

    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    // 增强的逻辑写到这里
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法之前执行
        System.out.println("方法之前执行......" + method.getName() + "" + Arrays.toString(args));
        // 执行你当前方法
        Object res = method.invoke(obj, args);

        System.out.println("方法之后执行......" + obj.getClass());

        return res;
    }
}